package cn.sylinx.hbatis.ext.transaction.springboot;

import java.lang.reflect.Method;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;

import cn.sylinx.hbatis.ext.transaction.AbstractTransactionalSupport;
import cn.sylinx.hbatis.ext.transaction.Transactional;
import cn.sylinx.hbatis.log.GLog;

@Aspect
@Component
public class TransactionAspect extends AbstractTransactionalSupport {

	@Pointcut("@annotation(cn.sylinx.hbatis.ext.transaction.Transactional)")
	public void hbatisSpringbootTransactionalAspect() {

	}

	@Around(value = "hbatisSpringbootTransactionalAspect()")
	public Object doAround(ProceedingJoinPoint pjp) throws Throwable {

		GLog.debug("hbatisSpringbootTransactionalAspect bingo");

		// 切点所在的类
		Class<?> targetClass = pjp.getTarget().getClass();
		// 使用了注解的方法
		String methodName = pjp.getSignature().getName();
		Class<?>[] parameterTypes = ((MethodSignature) pjp.getSignature()).getMethod().getParameterTypes();
		Method method = targetClass.getMethod(methodName, parameterTypes);
		
		return transaction(method.getAnnotation(Transactional.class), () -> pjp.proceed());
	}

}
